package com.nolon.flange

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.preference.PreferenceManager
import com.nolon.flange.adapter.MainPagerAdapter
import com.nolon.flange.databinding.ActivityMainBinding
import com.nolon.flange.extensions.toast
import com.nolon.flange.fragment.FileFragment
import com.nolon.flange.fragment.ProjectFragment
import com.nolon.flange.tools.isActivityTop
import com.nolon.flange.viewmodel.ProjectViewModel
import com.nolon.flange.viewmodel.ProjectViewModelFactory
import com.permissionx.guolindev.PermissionX
import java.util.*


class MainActivity : AppCompatActivity() {
    private val bd by lazy { ActivityMainBinding.inflate(layoutInflater) }

    lateinit var mainViewModel: ProjectViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(bd.root)
        // init database and get projectDao
        initView()
        bindData()
        invokePermission()
    }

    private fun invokePermission() {
        val sp = PreferenceManager.getDefaultSharedPreferences(this)
        val hasWritePermission = sp.getBoolean(getString(R.string.pref_write_permission), false)
        if (!hasWritePermission) {
            PermissionX.init(this)
                .permissions(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                )
                .onExplainRequestReason { scope, deniedList ->
                    val message = "法兰助手需要读写存储的权限来保存文件"
                    scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
                }
                .request { allGranted, _, _ ->
                    if (allGranted) {
                        val editor = sp.edit()
                        editor.putBoolean(getString(R.string.pref_write_permission), true)
                        editor.apply()
                    } else {
                        Toast.makeText(this, "请允许读写文件，否则无法正常工作", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
        }
    }

    private fun initView() {
        setSupportActionBar(bd.toolbar)
        supportActionBar?.apply {
            setHomeButtonEnabled(true)
            title = getString(R.string.flange_calculator)
        }
        val projectFragment = ProjectFragment(this)
        val fileFragment = FileFragment(this)
        val fragmentList =
            listOf<Fragment>(projectFragment, fileFragment)

        // Set up ViewPager and TabLayout
        val mainPagerAdapter =
            MainPagerAdapter(fragmentList, supportFragmentManager)
        bd.viewPager.apply {
            adapter = mainPagerAdapter
            bd.tabs.setupWithViewPager(this)
        }

        // 法兰算料按钮
        bd.fab.setOnClickListener(onAddClick)
        bd.fab.setOnLongClickListener {
            val intent = Intent(this, Main5Activity::class.java)
            startActivity(intent)
            true
        }

    }

    private val onAddClick: (View) -> Unit = {
        // 防止重复点击
        if (isActivityTop(this.javaClass, this)) {
            val dateNow = Calendar.getInstance()
            val expiredDate = Calendar.getInstance()
            expiredDate.set(2021, 3, 31)
            if (dateNow > expiredDate) {
                toast(this, getString(R.string.software_expired))
            } else {
                val intent = Intent(this@MainActivity, FlangeActivity::class.java).apply {
                    putExtra(IS_NEW_PROJECT, true)
                }
                startActivityForResult(intent, NEW_PROJECT_REQUEST)
            }
        }
    }


    private fun bindData(): Unit {
        val projectDao = AppDatabase.getInstance(application).projectDao
        val viewModelFactory = ProjectViewModelFactory(projectDao, application)
        mainViewModel = ViewModelProvider(this, viewModelFactory).get(ProjectViewModel::class.java)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == NEW_PROJECT_REQUEST && resultCode == RESULT_OK) {
            mainViewModel.refreshFiles(this)
        }
    }

    // 处理按钮点击
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                if (!isActivityTop(this.javaClass, this)) return false
                val intent = Intent(this, UserActivity::class.java)
                startActivity(intent)
            }
            R.id.toolbarSetting -> {
                if (!isActivityTop(this.javaClass, this)) return false
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
            }
        }
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        bd.toolbar.inflateMenu(R.menu.menu_main)
        return true
    }

    companion object {
        const val NEW_PROJECT_REQUEST = 1
        const val EDIT_PROJECT_REQUEST = 2
        const val PROJECT_ID = "PROJECT_ID"
        const val IS_NEW_PROJECT = "IS_NEW_PROJECT"
    }
}